package com.flea.web.vo.datatables;

import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.List;

/**
 * datatables 表格发送到服务器的数据封装
 */
@Getter
@Setter
public class DTInput {
	private static int DEFAULT_MAX_LENGTH = 9999;

	private int draw;
	private int start;
	private int length;
	private List<DTColumn> columns;
	private List<DTOrder> order;

	public List<DTColumn> getColumns() {
		return columns;
	}

	public void setColumns(List<DTColumn> columns) {
		this.columns = columns;
	}

	public List<DTOrder> getOrder() {
		return order;
	}

	public void setOrder(List<DTOrder> order) {
		this.order = order;
	}

	public int getDraw() {
		return draw;
	}

	public void setDraw(int draw) {
		this.draw = draw;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		if (length == -1)
			return DEFAULT_MAX_LENGTH;
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public String getOrderBy() {
		if (order == null || order.size() == 0 || order.get(0).getColumn() == null || columns == null) {
			return null;
		}
		return columns.get(order.get(0).getColumn()).getData();
	}

	public String getOrderDir() {
		if (order == null || order.size() == 0 || order.get(0).getColumn() == null || columns == null) {
			return null;
		}
		return order.get(0).getDir();
	}

	/**
	 * 返回页码，从0开始
	 */
	public int getPageNumber() {
		if (length == 0)
			length = 10;
		return start / length;
	}

	public PageRequest toPageRequest() {
		//获得排序方向 DESC or ASC
		Sort.Direction direction = Sort.Direction.fromString(getOrderDir());
		Sort sort = Sort.by(direction, getOrderBy());
		return PageRequest.of(getPageNumber(), getLength(), sort);
	}

}
